package yang.itcode.controller;

import cn.hutool.json.JSONObject;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import yang.itcode.model.Result;
import yang.itcode.service.SupplierService;

import static yang.itcode.constant.ErrorConstant.*;

@RestController
@RequestMapping("/api/supplier")
public class SupplierController {

    @Autowired
    private SupplierService supplierService;

    @PostMapping
    public Result<Object> addSupplier(@RequestBody JSONObject obj) {
        if (supplierService.addSupplier(obj)) {
            return Result.success();
        } else {
            return Result.error(SUPPLIER_ADD_EXCEPTION_CODE, SUPPLIER_ADD_EXCEPTION_MESSAGE);
        }
    }

    @PostMapping("/list")
    public Result<PageInfo<JSONObject>> getSupplierList(@RequestBody JSONObject obj) {
        Integer pageNum = obj.getInt("pageNum");
        Integer pageSize = obj.getInt("pageSize");
        JSONObject condition = obj.getJSONObject("condition");
        return Result.success(supplierService.getSupplierList(pageNum, pageSize, condition));
    }

    @GetMapping("/{id}")
    public Result<JSONObject> getSupplierDetail(@PathVariable("id") Integer id) {
        return Result.success(supplierService.getSupplierDetail(id));
    }

    @PutMapping
    public Result<Object> updateSupplier(@RequestBody JSONObject obj) {
        if (supplierService.updateSupplier(obj)) {
            return Result.success();
        } else {
            return Result.error(SUPPLIER_UPDATE_EXCEPTION_CODE, SUPPLIER_UPDATE_EXCEPTION_MESSAGE);
        }
    }

    @DeleteMapping("/{id}")
    public Result<Object> deleteSupplier(@PathVariable("id") Integer id) {
        if (supplierService.deleteSupplier(id)) {
            return Result.success();
        } else {
            return Result.error(SUPPLIER_DELETE_EXCEPTION_CODE, SUPPLIER_DELETE_EXCEPTION_MESSAGE);
        }
    }
}
